<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/WEB-INF/jsp/taglib.jsp" %>
<html>
<head>
    <c:import url="/WEB-INF/jsp/frontend/head.jsp"/>
    <title>chat</title>

</head>
<body>
<div style="margin: 20px auto; border: 1px solid blue; width: 300px; height: 500px;">

    <div id="msg" style="width: 100%; height: 70%; border: 1px solid yellow;overflow: auto;"></div>

    <textarea id="tx" style="width: 100%; height: 20%;"></textarea>

    <button id="send" style="width: 100%; height: 8%;">发送数据</button>

</div>

<c:import url="/WEB-INF/jsp/frontend/footer.jsp"/>
<c:import url="/WEB-INF/jsp/frontend/script.jsp"/>
<script src="<spring:url value="/js/sockjs.min.js"/>" type="text/javascript"></script>
<script>
    var websocket;

    // whether support WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket");
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://localhost:8080/websocket");
    } else {
        websocket = new SockJS("http://localhost:8080/sockjs/websocket");
    }

    <%--if ('WebSocket' in window) {--%>
    <%--websocket = new WebSocket("ws://<spring:url value='/websocket' />");--%>
    <%--} else if ('MozWebSocket' in window) {--%>
    <%--websocket = new MozWebSocket("ws://<spring:url value='/websocket' />");--%>
    <%--} else {--%>
    <%--websocket = new SockJS("<spring:url value='/sockjs/websocket' />");--%>
    <%--}--%>

    // on open
    websocket.onopen = function (evnt) {
        console.log("  websocket.onopen  ");
    };


    // on talk
    websocket.onmessage = function (evnt) {
        $("#msg").append("<p>(<font color='red'>" + evnt.data + "</font>)</p>");
        console.log("  websocket.onmessage   ");
    };

    // on error
    websocket.onerror = function (evnt) {
        console.log("  websocket.onerror  ");
    };

    // on close
    websocket.onclose = function (evnt) {
        console.log("  websocket.onclose  ");
    };


    // send
    $("#send").click(function () {

        var text = $("#tx").val();

        if (text == null || text == "") {
            alert(" content can not empty!!");
            return false;
        }

        var msg = {
            messageText: text,
            messageToId: "eb3ccf4c3dda4a4da6a5d65732780c1d"
        };

        websocket.send(JSON.stringify(msg));
    });

</script>
</body>
</html>

